#-*- coding: utf-8 -*-
import os
import logging

from nose.plugins import Plugin

from selenose.consts import LOGGER
from selenose.driver import Driver
from selenose.excepts import PluginError
from selenose.core import environ, startup, shutdown
from selenose.tools import geturl, set_options, geturlpath

# Get a logger
logger =  logging.getLogger('%s.%s' % (LOGGER, __name__))

class Selenose(Plugin, object):
    '''Django's Selenium test plugin for Nose'''

    def help(self):
        '''Help'''
        return "Django's Selenium test plugin for Nose"

    def options(self, parser, env=os.environ):
        '''Add launch options for plugin'''
        # Call super
        Plugin.options(self, parser, env)
        # Add options
        set_options(parser, binary=False)

    def configure(self, options, config):
        '''Configure the plug in'''
        # Call super
        Plugin.configure(self, options, config)
        # Store options
        self.opts = options

    def begin(self):
        '''Initialize the plug in'''
        # Check if start servers
        self.dev = self.opts.dev and os.path.isfile(geturlpath())
        # Keep logs or not
        self.keep = self.opts.keep
        # Set configuration
        environ(self.opts)
        # Check if start servers
        if not self.dev:
            # Get the web server number
            try: self.nbrs = max(int(self.opts.multiprocess_workers), 1)
            # Multiprocess plug in not enabled
            except: self.nbrs = 1
            # Startup
            self.grid, self.djangos, self.server = startup(self.opts, self.nbrs)
            # Get the URL
            self.url = self.server.geturl()

    def beforeTest(self, test):
        '''Set test driver before test'''
        # Get the fixtures
        fixtures = None
        # Check if test defile fixtures
        if hasattr(test.context, 'fixtures'):
            # Get test fixtures
            fixtures = test.context.fixtures
        # Get the URL
        if not self.dev: url = self.url
        # Server not started locally
        else:
            # Get the URL
            url = geturl()
            # Check if defined
            if url is None: raise PluginError('failed to find a selenose server')
        # Set driver in test context
        test.context.driver = Driver(url, fixtures)

    def afterTest(self, test):
        '''Stop server after test'''
        # Get the driver then stop server
        test.context.driver.stop()

    def finalize(self, result):
        '''Stop all process'''
        # Check if server started
        if not self.dev:
            # Stop servers
            shutdown(self.keep, self.grid, self.djangos, self.server)

